package cn.z2huo.knowledge.streamapi.findfirst;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.List;

class FindFirstMapTest {

    @Data
    @AllArgsConstructor
    static class Person {
        String name;
        Integer age;
    }

    public static void main(String[] args) {
        List<Person> list = List.of(
                new Person("zhang", 12),
                new Person("liu", 13),
                new Person("wang", null),
                new Person("li", 15)
        );

        // 下面这个代码会报错，因为 Stream.findFirst() 方法在被stream流选中的元素为null时，会报空指针异常
//        Integer age = list.stream().filter(x -> "wang".equals(x.getName()))
//                .map(Person::getAge)
//                .findFirst()
//                .orElse(999);

        Integer age = list.stream().filter(x -> "wang".equals(x.getName()))
                .findFirst()
                .map(Person::getAge)
                .orElse(999);

        System.out.println(age);

    }

}
